/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  DIBasePicActivity.java   
 * @Package com.jiyi.activity.datainput   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2018-1-11 上午9:44:17   
 * @version V1.0     
 */
package com.jiyi.activity.datainput;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jiyi.inteface.DownloadPicOverInterface;
import com.jiyi.inteface.PickPopInterface;
import com.jiyi.view.PickPopView;
import com.jiyi.widget.picselect.PicFloderList_Activity;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.jiyi.widget.picshow.ImagePagerActivity;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.PermissionUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.utils.CameraUtils;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: DIBasePicActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2018-1-11 上午9:44:17
 * 
 */
public class DIBasePicActivity extends ActivityBase implements PickPopInterface {
	private boolean isDelModel;
	private MyAdapter adapter;
	private int max = 4;
	private InputMethodManager imm;
	PickPopView mPickPopView;
	// 图片路径
	private Uri mCameraUri;
	// 拍摄事件
	public final int CAMARE_CODE = 1;
	// 从相册选择事件
	public final int CHOOSE_PICTURE = 2;
	// 图片路径
	private String filePath;
	// 加载的进度条
	Dialog dialog;
	Map<Integer, String> results = new HashMap<Integer, String>();

	GridView gvPic;
	
	DownloadPicOverInterface downloadPicOverInterface;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initTTT();
	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		PicSelectConstans.current.clear();
		PicSelectConstans.publish_pics.clear();
		super.onDestroy();
	}

	public void initTTT() {
		imm = DeviceUtil.getInstance().getImm();
		mPickPopView = new PickPopView(this, this);
	}

	@Override
	public void OnShootListener() {
		if(PermissionUtil.checkPermission(this,PermissionUtil.CARAME))
		{
			useCamere();
		}

	}

	@Override
	public void OnAlbumListener() {
		// 添加图片 从相册
		PicSelectConstans.headUrl = "";
		Intent intent = new Intent(this, PicFloderList_Activity.class);
		intent.putExtra("max", max);
		startActivityForResult(intent, CHOOSE_PICTURE);
		mPickPopView.hidePopWindow();
	}

	/**
	 * <p>
	 * Title: OnCancleListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnCancleListener()
	 */
	@Override
	public void OnCancleListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnShowListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnShowListener()
	 */
	@Override
	public void OnShowListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnHideListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnHideListener()
	 */
	@Override
	public void OnHideListener() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAMARE_CODE && resultCode == RESULT_OK) {
			if (!TextUtils.isEmpty(filePath)) {
				PicSelectConstans.publish_pics.add(filePath);
				refreshAdapter(gvPic);
			}
		} else if (requestCode == CHOOSE_PICTURE) {
			refreshAdapter(gvPic);
		}
	}

	@Override
	public void onBackPressed() {
		PicSelectConstans.current.clear();
		PicSelectConstans.publish_pics.clear();
		super.onBackPressed();
	}

	private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
		private final int position;

		public getImageCacheAsyncTask(int position) {
			this.position = position;
		}

		@Override
		protected File doInBackground(String... params) {
			String imgUrl = params[0];
			try {
				return Glide
						.with(context)
						.load(imgUrl)
						.downloadOnly(Target.SIZE_ORIGINAL,
								Target.SIZE_ORIGINAL).get();
			} catch (Exception ex) {
				return null;
			}
		}

		@Override
		protected void onPostExecute(File result) {
			if (result == null) {
				return;
			}
			// 此path就是对应文件的缓存路径
			String path = result.getPath();
			Log.e("path", path);
			PicSelectConstans.publish_pics.set(position, path);
			results.put(position, "2");
			if (isDownLoadSuccess()) {
				for (int i = 0; i < PicSelectConstans.publish_pics.size(); i++) {
					Log.e("ttt     ", PicSelectConstans.publish_pics.get(i)
							+ "\n");
				}
				// doPostPics();
				if (downloadPicOverInterface != null) {
					downloadPicOverInterface.post();
				}
			}
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	class MyAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			if (PicSelectConstans.publish_pics.size() > 0) {
				return PicSelectConstans.publish_pics.size() + 2;
			}
			return 1;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View inflate = getLayoutInflater().inflate(
					R.layout.simple_imageview, null);
			ImageView iv_simple = (ImageView) inflate
					.findViewById(R.id.iv_simple);
			ImageView iv_delpic = (ImageView) inflate
					.findViewById(R.id.iv_delpic);

			if (PicSelectConstans.publish_pics.size() <= 0) {
				iv_simple.setImageDrawable(getResources().getDrawable(
						R.mipmap.add_square));
			} else {
				if (position == PicSelectConstans.publish_pics.size()) {
					iv_simple.setImageDrawable(getResources().getDrawable(
							R.mipmap.add_square));
				} else if (position == PicSelectConstans.publish_pics.size() + 1) {
					iv_simple.setImageDrawable(getResources().getDrawable(
							R.mipmap.delpic));
				} else {
					if (isDelModel) {
						iv_delpic.setVisibility(View.VISIBLE);
					} else {
						iv_delpic.setVisibility(View.GONE);
					}

					String sourcePath = PicSelectConstans.publish_pics
							.get(position);
					GlideUtil.load(AppBase.Context, sourcePath, iv_simple);

				}
			}
			return inflate;
		}
	}

	protected void refreshAdapter(final GridView gvPic) {
		this.gvPic = gvPic;
		if (PicSelectConstans.publish_pics.size() <= 0) {
			isDelModel = false;
		}

		if (adapter == null) {
			adapter = new MyAdapter();
			float density = DeviceUtil.getInstance().getBiLi(); // 像素密度
			int screenWidth = DeviceUtil.getInstance().getScreenWidth();
			// 15是父节点的padding 2是左右两边
			screenWidth -= 15 * 2 * density;
			// 求出最大可放的图片个数 60是item的宽度 10是item之间的间距
			int maxNum = (int) Math.floor(screenWidth / ((60 + 10) * density));
			Log.e("maxNum ", maxNum + "");
			gvPic.setNumColumns(maxNum);
			gvPic.setAdapter(adapter);
			gvPic.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View view,
						int position, long arg3) {
					if (isDelModel) {
						if (PicSelectConstans.publish_pics.size() > 0) {

							if (position == PicSelectConstans.publish_pics
									.size()) {
								addPic(view);
							} else if (position == PicSelectConstans.publish_pics
									.size() + 1) {
								isDelModel = false;
								refreshAdapter(gvPic);
							} else {
								PicSelectConstans.publish_pics.remove(position);
								refreshAdapter(gvPic);
							}
						}
					} else {
						if (PicSelectConstans.publish_pics.size() <= 0) {
							addPic(view);
						} else {
							if (PicSelectConstans.publish_pics.size() == position) {
								addPic(view);
							} else if (PicSelectConstans.publish_pics.size() + 1 == position) {
								isDelModel = true;
								refreshAdapter(gvPic);
							} else {
								String[] urls = new String[PicSelectConstans.publish_pics
										.size()];
								for (int i = 0, n = PicSelectConstans.publish_pics
										.size(); i < n; i++) {
									urls[i] = PicSelectConstans.publish_pics
											.get(i);
								}

								Intent intent = new Intent(view.getContext(),
										ImagePagerActivity.class);
								intent.putExtra(
										ImagePagerActivity.EXTRA_IMAGE_URLS,
										urls);
								intent.putExtra(
										ImagePagerActivity.EXTRA_IMAGE_INDEX,
										position);
								startActivity(intent);
							}
						}
					}
				}
			});
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	private void addPic(View view) {
		if (PicSelectConstans.publish_pics.size() >= max) {
			ToastUtil.getInstances().showMsg("最多只能添加" + max + "张图片");
			return;
		}
		PicSelectConstans.pic_tag = 2;
		isDelModel = false;
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏键盘
		}
		PicSelectConstans.current.clear();
		if (PicSelectConstans.publish_pics.size() > 0) {
			PicSelectConstans.current.addAll(PicSelectConstans.publish_pics);
		}
		mPickPopView.showPopWindow();
	}

	/**
	 * @author: HYM
	 * @Title: downloadImage
	 * @Description: TODO(保存前重新下载线上的图片) void
	 * @date: 2018-1-11
	 */
	protected void downloadImage() {

		showDialog(dialog);
		// 清空任务记录
		results.clear();
		// 根据是否需要下载图片来处理保存
		boolean needDownload = false;
		// 图片数组
		int size = PicSelectConstans.publish_pics.size();
		for (int i = 0; i < size; i++) {
			if (PicSelectConstans.publish_pics.get(i).contains("http")) {
				needDownload = true;
				results.put(i, "1");
				new getImageCacheAsyncTask(i)
						.execute(PicSelectConstans.publish_pics.get(i));
			}
		}

		if (!needDownload) {
			for (int i = 0; i < PicSelectConstans.publish_pics.size(); i++) {
				Log.e("ttt     ", PicSelectConstans.publish_pics.get(i) + "\n");
			}
			// doPostPics();
			if (downloadPicOverInterface != null) {
				downloadPicOverInterface.post();
			}
		}

	}

	boolean isDownLoadSuccess()

	{
		for (Integer i : results.keySet()) {
			if (results.get(i).equals("1")) {
				return false;
			}
		}
		return true;
	}

	protected DownloadPicOverInterface getDownloadPicOverInterface() {
		return downloadPicOverInterface;
	}

	protected void setDownloadPicOverInterface(
			DownloadPicOverInterface downloadPicOverInterface) {
		this.downloadPicOverInterface = downloadPicOverInterface;
	}

	private void useCamere()
	{
		File fileDir = new File(AppConfig.DIR_IMAGE);
		if (!fileDir.exists())
		{
			fileDir.mkdirs();
		}

		filePath = AppConfig.DIR_IMAGE+"temp"+new Date().getTime()+".jpg";
		File file = new File(filePath);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
		{
			mCameraUri = FileProvider.getUriForFile(this,"com.swift.maintenance.updateprovider",file);
		}
		else
		{
			mCameraUri = CameraUtils.getOutputMediaFileUri(CameraUtils.MEDIA_TYPE_IMAGE);
			filePath=mCameraUri.getPath();
		}
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");



		intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraUri);
		startActivityForResult(intent, CAMARE_CODE);
		mPickPopView.hidePopWindow();
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == PermissionUtil.CARAME)
		{
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)
			{
				useCamere();
			}
			else
			{
				ToastUtil.getInstances().showMsg("无法访问相机");
			}
		}
	}
}
